package com.cc.visitor.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.TreeMap;
/**
 * @author chanchaw
 * @create 2025-03-15 19:24
 */
public class RequestValidator {

    private static final String HMAC_SHA256 = "HmacSHA256";

    /**
     * 生成签名
     */
    public static String generateSignature(Map<String, String> params, String secretKey) {
        // 1. 按字典序排序参数
        Map<String, String> sortedParams = new TreeMap<>(params);

        // 2. 拼接参数字符串
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        String paramString = sb.toString();
        if (paramString.endsWith("&")) {
            paramString = paramString.substring(0, paramString.length() - 1);
        }

        // 3. 使用 HMAC-SHA256 生成签名
        try {
            Mac mac = Mac.getInstance(HMAC_SHA256);
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), HMAC_SHA256);
            mac.init(secretKeySpec);
            byte[] signatureBytes = mac.doFinal(paramString.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(signatureBytes);
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate signature", e);
        }
    }

    /**
     * 验证签名
     */
    public static boolean validateSignature(Map<String, String> params, String clientSignature, String secretKey) {
        String serverSignature = generateSignature(params, secretKey);
        return serverSignature.equals(clientSignature);
    }
}